package com.maoxx.sb_vue_blog.shiro;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.maoxx.sb_vue_blog.common.lang.Result;
import com.maoxx.sb_vue_blog.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.SocketTimeoutException;

@Component
@Slf4j
public class JwtFilter extends AuthenticatingFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        //获取请求token
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String jwt = request.getHeader("authorization");

        if (StringUtils.isEmpty(jwt)) {
            return null;
        }
        return new JwtToken(jwt);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        //获取请求token
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String jwt = request.getHeader("authorization");

        if (StringUtils.isEmpty(jwt)) {
            return true;
        } else {
            // 验证token是否有效
            Claims claim = jwtUtils.getClaimByToken(jwt); // 获取token中的payload

            if (claim == null || jwtUtils.isTokenExpired(claim.getExpiration())) {
                // 无效token
                throw new ExpiredCredentialsException("token已过期");
            }
            // 执行登录
            try {
                // 尝试捕获可能发生的SocketTimeoutException
                return executeLogin(servletRequest, servletResponse);
            } catch (SocketTimeoutException e) {
                // 处理连接超时异常，例如记录日志或返回错误信息
                log.error("连接超时: ", e);
                // 根据业务逻辑，可以返回false或抛出异常
                return false;
            }
        }

    }


    // 登陆失败进行处理
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {

        HttpServletResponse resp = (HttpServletResponse) response;

        // 获取失败的原因
        Throwable throwable = e.getCause() == null ? e : e.getCause();

        // 打包成result格式
        Result result = Result.fail(throwable.getMessage());

        // 转成json字符串
        String json = StrUtil.toString(result);

        // 输出到前端
        try {
            resp.getWriter().print(json);
        } catch (IOException ex) {

        }

        // 返回false，表示已经处理了
        return false;
    }


    // 再过滤前进行跨域处理
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个OPTIONS请求，这里我们给OPTIONS请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(org.springframework.http.HttpStatus.OK.value());
            return false;
        }

        return super.preHandle(request, response);
    }
}
